package com.kbtx;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.FileProvider;

import java.io.File;

public class AppInstaller2 {
    /**
     * Install .apk file.
     *
     * @param context needed to ask for permission
     */
    public static void installApk(
            final @NonNull File file, final @NonNull Context context) {
        // 新版apk安装逻辑
        // 参考 https://github.com/TeamAmaze/AmazeFileManager
        // 的 app/src/main/java/com/amaze/filemanager/filesystem/files/FileUtils.java : 456行附近
        Intent intent = new Intent(Intent.ACTION_VIEW);
        String type = "application/vnd.android.package-archive";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri downloadedApk = FileProvider.getUriForFile(
                context.getApplicationContext(), context.getPackageName(), file);
            intent.setDataAndType(downloadedApk, type);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            intent.setDataAndType(Uri.fromFile(file), type);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        try {
            context.startActivity(intent);
        } catch (Exception e) {
            Log.w("failed to install apk", e);
            Toast.makeText(context, "应用安装失败", Toast.LENGTH_SHORT).show();
        }
    }
}
